package com.big_data_studio.service.impl;

import com.big_data_studio.entity.Oss;
import com.big_data_studio.mapper.OssMapper;
import com.big_data_studio.service.IOssService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.big_data_studio.util.string_utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 对象存储 服务实现类
 * </p>
 *
 * @author PC
 * @since 2022-10-16
 */
@Service
public class OssServiceImpl extends ServiceImpl<OssMapper, Oss> implements IOssService {

    @Autowired
    OssMapper ossMapper;

    @Value("${reggie.path}")
    String folder;

    @Override
    public String uploadMarkdownImg(MultipartHttpServletRequest file) {
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getFile("image").getOriginalFilename()
                .substring(file.getFile("image").getOriginalFilename().length() - 4));
        if (!f.isDirectory()) {
            f.mkdirs();
        }
        try {
            file.getFile("image").transferTo(f);
            return "http://localhost:9090/api/file/" + f.getName();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public String uploadImg(MultipartFile file) {
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:9090/api/file/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
